//
//  HomeTableViewController.swift
//  Weibo
//
//  Created by 梁智 on 15/11/21.
//  Copyright © 2015年 lzfree. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 原创微博 Cell 的可重用标示符号
let StatusCellNormalId = "StatusCellNormalId"
/// 转发微博 Cell 的可重用标示符号
let StatusCellRetweetedId = "StatusCellRetweetedId"

class HomeTableViewController: VisitorTableViewController {

    /// 微博数据列表模型
    private lazy var listViewModel = StatusListViewModel()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !UserAccountViewModel.sharedUserAccount.userLogin {
            visitorView?.setupInfo(nil, title: "关注一些人，回这里看看有什么惊喜")
            return
        }
        
        prepareTableView()
        
        loadData()
        
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserverForName(WBStatusSelectedPhotoNotification,
            object: nil,
            queue: nil) { [weak self] (n) -> Void in
            
                guard let indexPath = n.userInfo?[WBStatusSelectedPhotoIndexPathKey] as? NSIndexPath else {
                    return
                }
                guard let urls = n.userInfo?[WBStatusSelectedPhotoURLsKey] as? [NSURL] else {
                    return
                }
                // 判断 cell 是否遵守了展现动画协议！
                guard let cell = n.object as? PhotoBrowserPresentDelegate else {
                    return
                }
                print("选择 照片 cell \(cell)")
                
                let vc = PhotoBrowserViewController(urls: urls, indexPath: indexPath)
                // 1. 设置modal的类型是自定义类型 Transition(转场)
                vc.modalPresentationStyle = UIModalPresentationStyle.Custom
                // 2. 设置动画代理
                vc.transitioningDelegate = self?.photoBrowserAnimator
                // 3. 设置 animator 的代理参数
                self?.photoBrowserAnimator.setDelegateParams(cell, indexPath: indexPath, dismissDelegate: vc)
                
                self?.presentViewController(vc, animated: true, completion: nil)
        }
    }
    
    // 注销通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /// 准备表格
    private func prepareTableView() {
        // 注册可重用 cell
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: StatusCellNormalId)
        tableView.registerClass(StatusRetweetedCell.self, forCellReuseIdentifier: StatusCellRetweetedId)
        
        // 取消分割线
        tableView.separatorStyle = .None
        
        // 自动计算行高
        tableView.estimatedRowHeight = 400
        
        // 下拉刷新
        refreshControl = WBRefreshControl()
        // 添加监听方法
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        // 上拉刷新视图
        tableView.tableFooterView = pullupView
    }
    
    /// 加载数据
    @objc private func loadData() {
        
        //refreshControl?.beginRefreshing()
        
        listViewModel.loadStatus(isPullup: pullupView.isAnimating()) { (isSuccessed) -> () in
            
            // 关闭刷新控件
            self.refreshControl?.endRefreshing()
            self.pullupView.stopAnimating()
            
            if !isSuccessed {
                SVProgressHUD.showInfoWithStatus("加载数据错误,请稍候再试")
                return
            }
            
            
            self.tableView.reloadData()
            
            //print(self.listViewModel.statusList)
        }
        
    }
    
    // MARK: - 懒加载控件
    /// 上拉刷新提示视图
    private lazy var pullupView: UIActivityIndicatorView = {
        
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        indicator.color = UIColor.lightGrayColor()
        
        return indicator
    }()
    /// 照片浏览转场动画代理
    private lazy var photoBrowserAnimator: PhotoBrowserAnimator = PhotoBrowserAnimator()
}

// MARK: - 数据源方法
extension HomeTableViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let vm = listViewModel.statusList[indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(vm.cellId, forIndexPath: indexPath) as! StatusCell
        
        cell.viewModel = vm
        
        // 判断是否需要上拉刷新
        if indexPath.row == listViewModel.statusList.count - 1 && !pullupView.isAnimating() {
            print("应该上拉刷新了")
            pullupView.startAnimating()
            // 上拉刷新数据
            loadData()
        }
        
        return cell
    }
    
    // 行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return listViewModel.statusList[indexPath.row].rowHeight
    }
}
